package com.zzyl.intercept;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.PathMatcherUtil;
import com.zzyl.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理端拦截器
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenProperties jwtTokenProperties;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Authorization");

        if (StrUtil.isEmpty(token)) {
            System.out.println(request.getRequestURL());
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //解析token
        Map<String, Object> claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), token);
        if (ObjectUtil.isEmpty(claims)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        Long id = Long.valueOf(claims.get("id").toString());
        ThreadLocalUtil.set(id);

        if (ObjectUtil.isEmpty(id)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        String s2 = stringRedisTemplate.opsForValue().get("path:request" + id);
        List<String> list = JSONUtil.toList(s2, String.class);

        String Url = StrUtil.concat(true, request.getMethod(), request.getRequestURI());
        boolean match = PathMatcherUtil.match(list,Url);
        if(!match){
            throw new RuntimeException("无权限访问");
        }

        return true;
    }
}